import React, { Component } from 'react'
import {Upload, Icon, Modal, message, Button, Tooltip} from 'antd';
import globalConfig from '../../config'
import Utils from '../../utils/utils'
import PropTypes from 'prop-types'
import Logger from '../../utils/Logger'
import './uploader.scss'
const logger = Logger.getLogger('Uploader');

let i = 0;
let showMessage = true;
class Uploader extends Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
    actionUrl: '',
  };
  componentWillMount() {
    const {type, url} = this.props;
    const UploaderTypeBoolean = type === 'image'
    if (UploaderTypeBoolean) {
      this.UploaderType = 'picture-card'
    } else {
      this.UploaderType = 'text'
    }
    if (url) {
      
    } else {
      this.uploaderUrl = `${globalConfig.getAPIPath()}${UploaderTypeBoolean ? globalConfig.upload.image : globalConfig.upload.file}`
    }
    // 看看是否做了大小限制
    if (this.props.sizeLimit) {
      this.sizeLimit = this.props.sizeLimit;
    } else {
      // 默认的大小限制
      if (UploaderTypeBoolean) {
        this.sizeLimit = globalConfig.upload.imageSizeLimit;
      } else {
        this.sizeLimit = globalConfig.upload.fileSizeLimit;
      }
    }

    // 允许上传的文件类型
    if (this.props.accept) {
      this.accept = this.props.accept;
    } else if (UploaderTypeBoolean) {
      this.accept = '.jpg,.png,.gif,.jpeg'; // 上传图片时有默认的accept
    }

    this.UploaderTypeBoolean = UploaderTypeBoolean
  }

  handleChange = ({file, fileList}) => {
    const {max} = this.props;
    // 在这个地方要把i重置
    // 限制个数
    fileList = fileList.slice(-max);
    // 第一遍的时候 也要进行判断
    if((this.sizeLimit && file.size / 1024 > this.sizeLimit)) {
      console.log(this.state)
      fileList = fileList.filter(v => v.uid !== file.uid)
      message.error(`${this.UploaderType ? '图片' : '文件'}过大，最大只允许${this.sizeLimit}KB`);
      return false;
    }

    fileList = fileList.map((file) => {
      if (file.response && file.response.code === 0) {
        file.url = file.response.url;
      }
      return file;
    });

    if(file.status === 'error') {
      message.error(`${file.name}上传失败`, 2.5);
    }

    if(file.status === 'done' || file.status === 'removed') {
      this.resetSet()
      this.noticFileChange()
    }
    this.setState({ fileList });
  }

    /**
   * 调用上传接口之前校验一次
   *
   * @param file
   * @returns {boolean}
   */
  beforeUpload = (file,fileList) => {
    i++;
    const {max} = this.props;
    fileList = fileList.slice(-max);
    if((this.sizeLimit && file.size / 1024 > this.sizeLimit)) {
      fileList = fileList.filter(v => v.uid !== file.uid)
      message.error(`${this.UploaderType ? '图片' : '文件'}过大，最大只允许${this.sizeLimit}KB`);
      return false;
    }
    // 限制个数
    if((i > max || (i > fileList.length && !showMessage))) {
      // 第一次进来之后 只能提示一次 后面再错就不要重复提示了...
      fileList = fileList.filter(v => v.uid !== file.uid)
      if(showMessage) {
        showMessage = false;
          message.error(`${this.UploaderType ? '图片' : '文件'}上传出错，只允许上传${max}${this.UploaderType ? '张' : '个'}`);
      }
      return false;
    } else {
      return true;
    }

  };

  resetSet = () => {
    // 这个地方重置下提示开关
    i = 0;
    showMessage = true;
  }

  // 上传成功或者删除文件的时候触发的事件
  noticFileChange = () => {
    const {onChange, max} = this.props;
    if (onChange) {
      let res;
      if (max === 1) {
        if (this.state.fileList.length > 0 && this.state.fileList[0].status === 'done') {
          res = this.state.fileList[0].url;
        } else {
          res = '';
        }
      } else {
        res = this.state.fileList.filter(file => file.status === 'done').map(file => file.url);
      }
      onChange(res)
    }
  }
 
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    // 这个地方因为是没有用cdn 所以只接用data/image就ok了
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  // 因为进来的type不同所以处理btn渲染的样式也是不同的
  renderUploadButton() {
    const {fileList} = this.state;
    const {btnIcon, max,btnText, placeholder} = this.props;
     let valBtnText = btnText ? btnText : "点击上传";
     let valBtnIcon = btnIcon ? btnIcon : 'plus';
    const showUploaderBtn = fileList.length >= max;
    if (this.UploaderTypeBoolean) {
      // 超出个数要判断
      if(showUploaderBtn) {
        return null
      }
      // 渲染button
      const button = (
        <div>
          <Icon type={valBtnIcon} />
          <div className="ant-upload-text">{valBtnText}</div>
        </div>
      )
      // 渲染tooltip
      if(placeholder) {
        return (
          <Tooltip title={placeholder} arrowPointAtCenter>
            {button}
          </Tooltip>
        )
      }
    } else {
      const button = <Button disabled={showUploaderBtn}><Icon type={valBtnIcon}/>{valBtnText}</Button>;
      if (this.props.placeholder && !showUploaderBtn) {
        return <Tooltip title={this.props.placeholder} mouseLeaveDelay={0}>
          {button}
        </Tooltip>;
      } else {
        return button;
      }
    }
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const {name,max} = this.props;
    return (
      <div>
        <Upload
          name={name}
          action={this.uploaderUrl}
          multiple={max > 1 ? true : false }
          beforeUpload={this.beforeUpload}
          listType={this.UploaderType}
          fileList={fileList}
          accept={this.accept}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {this.renderUploadButton()}
        </Upload>
        {
          this.UploaderTypeBoolean &&
          <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          </Modal>
        }

      </div>
    )
  }
}

Uploader.propTypes = {
  max: PropTypes.number.isRequired,
}
export default Uploader